var Promise = require('promise');
const apiLib = require('./MainApi');
module.exports = {

    index: function (req, res) {
      if (!req.session.userId) {
        return res.redirect('admin/login');
      }
      console.log(req.session.userId);
      return res.view('admin/index', {layout: 'admin/layout'});
      // var promise = List.query('select * from list', function (err, rawResult) {
      //   if (err) {return res.serverError(err)}
      //   //console.log(rawResult);
      //
      //   res.view('admin/index', {layout: 'admin/layout', data: rawResult});
      //   console.log(rawResult);
      //   return rawResult;
      // });
      // console.log();
    },

    login: function (req, res) {
      console.log(1)
      console.log(req.body);
      Admin.query('select * from admin where name = ?', req.body.username, function (err, result) {
        if (err) {return res.serverError(err);}

        console.log(result[0].password);

        if (result[0].password == req.body.password) {
          req.session.role = result[0].role;
          req.session.userId = result[0].id;
          return res.redirect('admin/index');
        }


        return res.view('admin/login', {layout: 'admin/layout_login', data: '密码错误！'});
      });
      //req.session.userId = 'userid';
      //return res.redirect('admin/index');

      //res.view('admin/login', {layout: 'admin/layout_login'});
    },

    orderAll: function (req, res) {
      Order.find().then(function (results) {
        var contacts = [];

        for (var i=0; i<results.length; i++) {
          contacts.push(Contact.find({id: results[i].id}));
        }
        Promise.all(contacts).then(function (contact) {
          return res.view('admin/order', {layout: 'admin/layout', data: results, contact: contact});
        })
      })
    },

    logout: function (req, res) {
      if (req.session.userId) {
        req.session.userId = void(0);
        console.log(req.session.userId);
        return res.redirect('admin/login');
      }
      return res.redirect('admin/login');
    },

    viewOrder: function (req, res) {
      Order.find({id: req.body.orderId}).then(function (results) {
        if (!results) {
          res.send('no products');
        } else {
          return res.send(results);
        }
      })
    },

    // orderDetail: function (req, res) {
    //   var orderId = req.params.id;
    //   Order.find({id: orderId}).then(function (result) {
    //     var detail = result[0];
    //     Contact.find({id: orderId}).then(function (result) {
    //       res.send({info: detail, contact: result});
    //     })
    //   })
    // },

    //订单拆分至箱
    orderSplit: function (req, res) {
      var orderId = req.params.id;
      Order_product.find({order_id: orderId}).then(function (result) {
        var info = [];
        for (var i=0; i<result.length; i++) {
          info.push(Product.find({sn: result[i].product_id}));
        }
        Promise.all(info).then(function (info) {
          return res.view('admin/split', {layout: 'admin/layout', orderProduct: result, productInfo: info});
        })
      })
    },

    featuredBrand: function (req, res) {
      var brand = req.params.brand;
      console.log(brand, 'this is brand');
      FeaturedBrand.findOrCreate({brand:brand, _sort: 1},{brand: brand, _sort: 1}).exec(function (err, result) {
        if (err) return res.serverError(err);
        console.log(result);
        res.ok('ok');
      })
    },

    cancelFeatured: function (req, res) {
      var brand = req.params.brand;
      FeaturedBrand.destroy({brand: brand}).then(function (result) {
        console.log(result);
        res.ok('ok')
      }).catch(function (err) {
        res.serverError(err);
      })
    },

  productAll: function (req, res) {
      res.view('admin/all_product', {layout: 'admin/layout'});
  },

  getAllProducts: function (req, res) {
    apiLib.getAllProducts(function (call) {
      res.send(JSON.parse(call));
    })
  },

  classify: function (req, res) {
    var body = req.body;
    Classify.create(body).then(function (created) {
      console.log('created product group:',created);
      res.send('ok');
    })
  },

  classified: function (req, res) {
    Classify.find({parent_id: 1}).then(function (records) {
      res.view('admin/classified_products', {layout: 'admin/layout', data: records});
    })
  },

  getClassify: function (req, res) {
    var p_sn = req.param('sn');
    Classify.find({parent_sn: p_sn}).then(function (record) {
      console.log(record);
      var c_sn = JSON.parse(record[0].child_sn);
      var c_products = [];
      var get_products_info = new Promise(function (resolve, reject) {
        for(var i=0; i<c_sn.length; i++){
          var get_product_info = new Promise(function (resolve, reject) {
            apiLib.getProductBySn(c_sn[i], function (info) {
              if(info && info.length > 0) {
                resolve(JSON.parse(info)[0])
              } else {
                reject('err');
              }
            })
          });
          Promise.all([get_product_info]).then(function (result) {
            c_products.push(result[0]);
            if (c_products.length == c_sn.length) {
              resolve(c_products);
            }
          })
        }
      });
      Promise.all([get_products_info]).then(function (result) {
        console.log(result);
        res.send(result[0]);
      })
    })
  },

  featureProduct: function (req, res) {
    res.view('admin/feature_product', {layout: 'admin/layout'});
  },

  featureIt: function (req, res) {
    var feature_name = req.body.feature;
    var list = req.body.p_list;
    console.log('list :',list)
    Feature.find({feature: feature_name}).then(function (record) {
      if (record.length > 0) {
        Feature.destroy({feature: feature_name}).exec(function (err, call) {
          if (err) return res.serverError(err);
          Feature.create({feature: feature_name, product: list}).then(function (created) {
            console.log('create new featured products:',created);
            res.send('ok');
          })
        })
      } else {
        Feature.create({feature: feature_name, product: list}).then(function (created) {
          console.log('created new products',created);
          res.send('ok');
        })
      }
    })
  }
}
